package com.laowang.controller;

import com.laowang.constant.CookieConstant;
import com.laowang.constant.RedisConstant;
import com.laowang.dataoject.SellerInfo;
import com.laowang.enums.ResultEnum;
import com.laowang.sercice.SellerService;
import com.laowang.utils.CookieUtil;
import org.hibernate.type.PrimitiveCharacterArrayClobType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2019/1/25.
 */
@Controller
@RequestMapping("/seller")
public class SellerInfoController {
    @Autowired
    private SellerService sellerService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid
                                , Map<String,Object> map
                                 , HttpServletResponse response){
        SellerInfo sellerInfo = sellerService.findSellerInfoByOpenid(openid);
        if(sellerInfo==null){
            map.put("msg", ResultEnum.LOGIN_ERROR.getMessage());
            map.put("url","sell/seller/order/list");
            return new ModelAndView("common/error",map);
        }
     //设置token到redis
        String token = UUID.randomUUID().toString();
        Integer expire= RedisConstant.EXPIRE;
        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX,token),openid,expire, TimeUnit.SECONDS);
     //设置token到cookie
        CookieUtil.set(response, CookieConstant.TOKEN,token,expire);
        return  new ModelAndView("/seller/order/list");
    }

    //登出
    @GetMapping("/logOut")
    public ModelAndView logOut(HttpServletRequest request,
                               HttpServletResponse response,
                               Map<String,Object> map){
        //获取cookie
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);

        if(cookie!=null){
            //清除cookie
            CookieUtil.set(response,CookieConstant.TOKEN,null,0);
            //清除token
            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
        }
        map.put("msg",ResultEnum.LOGINOUT.getMessage());
        map.put("url","/sell/seller/order/list");
        return  new ModelAndView("common/success",map);
    }
}
